import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '../router'
import { get_timeStamp } from './auth'

const TimeOut = 3600 * 1000 //定义token过期时间为1小时

const service = axios.create({
  // VUE_APP_BASE_API 从.env.development 或 .env.production 文件中获取
  baseURL: process.env.VUE_APP_BASE_API, // VUE_APP_BASE_API值 会自动和 本地http://localhost:8888 拼接在一起
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      if(Date.now() - get_timeStamp() > TimeOut) {
        // 如果token过期
        store.dispatch('user/logout')
        router.push('/login')
        return Promise.reject(new Error('token过期, 请重新登录'))
      }
      config.headers['Authorization'] = `Bearer ${store.getters.token}`
    } 
    return config
  },
  error => {
    // do something with request error
    console.log(error) 
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    // axios默认加了一层data
    if (response.data instanceof Blob) {
      return response.data
    }
    const { success, code, message, data } = response.data
    // message为boolean值
    if (success) {
      return data
    } else {
      Message.error(message)
      console.log(response.data)
      return Promise.reject(response.data)
    }
  },
  error => {
    Message.error(error.response.data.message || error.message)
    if(error.response.status === 401) {
      store.dispatch('user/logout')
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

export default service
